local class = reload("class")
local other = require("other")
local battles = reload("global.battles")
local super = reload("super.basic")
local movie = reload("pulgins.game.single.movie")


---@class cross_battle
local this = class(super)

---对象释放
function this:gcback()
    super.gcback(self)
    local arg = self.arg
    arg.battle = nil
    battles.map[arg.id] = nil
end

---创建战斗数据
function this:create(arg)
    arg.bt = self
    arg.maxRound = arg.maxRound or 30
    arg.roundSec = arg.maxRound or 120
    arg.acamp = {} --a阵营 pvp:发起者 pve:玩家
    arg.bcamp = {} --b阵营 pvp:接收方 pve:怪物
    ---记录战斗
    arg.batid = battles.id + 1
    battles.id = arg.batid
    battles.map[arg.batid] = arg
end

---删除战斗数据
function this:delete(arg)
    battles.map[arg.batid] = nil
end

---构造函数
function this:ctor()
    super.ctor(self)
end

function this:launch(arg)
    super.launch(self)
    self:async(self.mainProc, arg)
end

function this:joinACamp(arg, obj)
    table.insert(arg.acamp, obj)
end

function this:joinBCamp(arg, obj)
    table.insert(arg.bcamp, obj)
end

---遍历所有对象
function this:for2Camp(callback, that, ...)
    for sort, obj in ipairs(self._acamp) do
        callback(that, true, sort, obj, ...)
    end
    for sort, obj in ipairs(self._bcamp) do
        callback(that, false, sort, obj, ...)
    end
end

---遍历a阵营对象
function this:forACamp(callback, that, ...)
    for sort, obj in ipairs(self._acamp) do
        callback(that, true, sort, obj, ...)
    end
end

---遍历b阵营对象
function this:forBCamp(callback, that, ...)
    for sort, obj in ipairs(self._acamp) do
        callback(that, false, sort, obj, ...)
    end
end

function self:isOver(arg)
    ---判断最大回合数量
    if arg.round >= arg.maxRound then
        return true
    end

    ---判断战斗是否超时
    local now = other.nowsec()
    if now >= arg.endTime then
        return true
    end

    ---判断a阵营是否阵亡
    if self:isACampDead(arg) then
        return true
    end

    ---判断b阵营是否阵亡
    if self:isBCampDead(arg) then
        return true
    end

    return false
end

function this:isCampDead(camp)
    for _, obj in ipairs(camp) do
        if obj:isLive() then
            return false
        end
    end
    return true
end

function this:isACampDead(arg)
    return self:isCampDead(arg.acamp)
end

function this:isBCampDead(arg)
    return self:isCampDead(arg.bcamp)
end

---战斗处理过程
function this:mainProc(arg)
    ---战斗初始处理
    ---广播战斗开始
    ---战斗循环处理
    arg.round = 0
    while self:isOver(arg) do
        arg.round = arg.round + 1
        movie:mainProc(arg)
    end
    self:calcProc(arg)
end

function this:calcProc(arg)
    ---结算技能经验
    self:calcSkillExpProc(arg)
    ---结算战斗经验
    self:calcRolesExpProc(arg)
    ---结算战斗掉落
    self:calcFallingProc(arg)
    ---删除战斗
    self:delete(arg)
end

return this
